package com.fw.application.controller.v2.shop.read;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.BaseController;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.vo.TaskContentVo;
import com.fw.system.web.model.vo.v2.RedPackageLogVo;
import com.fw.system.web.service.*;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 红包类型表 前端控制器
 * </p>
 *
 * @author
 * @since 2021-09-03
 */
@RestController
@RequestMapping("/read/package")
@Api(tags = "拉新红包相关接口")
@CrossOrigin
public class V2ReadPackageController implements BaseController {


    @Autowired
    private IFwReadPackageService readPackageService;
    @Autowired
    private IFwReadPackageLogService readPackageLogService;
    @Autowired
    private IFwReadPackageTaskService readPackageTaskService;
    @Autowired
    private IFwReadPackageTaskContentService readPackageTaskContentService;
    @Autowired
    private IdXD idXD;
    @Autowired
    private IFwMoneysService moneysService;
    @Autowired
    private IFwLogsService logsService;
    //为用户领取红包

    @GetMapping("/addPackageByUser")
    @ApiOperation("检测用户有没有领取红包 没有领取 有直接到红包页面(有个截止倒计时结束) 或isState 为0 标志本轮红包用户结束 红包id")
    public Result<RedPackageLogVo> addPackageByUser(@RequestParam String id) {

        String userId = this.getUser().getId();
        FwReadPackage readPackage = readPackageService.getOne(Wrappers.<FwReadPackage>lambdaQuery().eq(FwReadPackage::getIsState, 1));
        FwReadPackageLog packageLog = readPackageLogService.getOne(Wrappers.<FwReadPackageLog>lambdaQuery().eq(FwReadPackageLog::getUserId, userId).eq(FwReadPackageLog::getReadId, id));
        RedPackageLogVo build = Builder.of(RedPackageLogVo::new).build();
        if (packageLog == null) {
            packageLog = Builder.of(FwReadPackageLog::new)
                    .with(FwReadPackageLog::setId, idXD.nextId())
                    .with(FwReadPackageLog::setCreateTime, LocalDateTime.now())
                    .with(FwReadPackageLog::setAmountNum, readPackage.getAmountNum())
                    .with(FwReadPackageLog::setUserId, userId)
                    .with(FwReadPackageLog::setEndTime, readPackage.getEndTime())
                    .with(FwReadPackageLog::setStartNum, readPackage.getStartNum())
                    .with(FwReadPackageLog::setReadId, readPackage.getId())
                    .with(FwReadPackageLog::setIsState, 1).build();
            packageLog.insert();
            BeanUtil.copyProperties(packageLog, build);
            build.setCheckState(true);
        } else {
            BeanUtil.copyProperties(packageLog, build);
             if (packageLog != null && packageLog.getIsState().equals(4)) {
                build.setIsState(4);
            } else {
                if (packageLog != null && packageLog.getStartNum().compareTo(readPackage.getAmountNum()) >= 0) {
                    build.setOpen(true);
                    build.setIsState(3);
                } else {
                    build.setIsState(2);
                }
            }
        }
        BigDecimal bigDecimal = packageLog.getAmountNum().multiply(new BigDecimal("100")).subtract(packageLog.getStartNum().multiply(new BigDecimal("100")));
        build.setDifference(bigDecimal.divide(new BigDecimal("100")));
        return success(build);
    }


    @GetMapping("/getTaskListByUser")
    @ApiOperation("拉取红包关联的任务列表和用户完成情况 红包id")
    public Result<List<TaskContentVo>> getTaskListByUser(@RequestParam String id) {
        List<FwReadPackageTask> list1 = readPackageTaskService.list();
        ArrayList<TaskContentVo> list2 = Lists.newArrayList();
        for (FwReadPackageTask task : list1) {
            List<FwReadPackageTaskContent> list = readPackageTaskContentService.list(Wrappers.<FwReadPackageTaskContent>lambdaQuery().eq(FwReadPackageTaskContent::getUserId, this.getUser().getId())
                    .eq(FwReadPackageTaskContent::getTaskId, task.getId()));
            TaskContentVo build = Builder.of(TaskContentVo::new).with(TaskContentVo::setId, task.getId()).with(TaskContentVo::setTaskName, task.getTaskName()).with(TaskContentVo::setTaskNum, task.getTaskNum()).build();
            build.setUserNum(list.size());
            build.setTaskAmount(task.getTaskAmount());
            list2.add(build);
        }

        return success(list2);
    }

    @GetMapping("/taskCommit")
    @ApiOperation("任务完成回调 任务id")
    public Result taskCommit(@RequestParam String id, String userId) {

        FwReadPackageTask packageTask = readPackageTaskService.getById(id);
        if (StringUtils.isBlank(userId))
            userId = this.getUser().getId();
        FwReadPackageLog packageLog = new FwReadPackageLog();
        if (packageTask != null){
             packageLog = readPackageLogService.getOne(Wrappers.<FwReadPackageLog>lambdaQuery().eq(FwReadPackageLog::getUserId, userId).eq(FwReadPackageLog::getReadId, packageTask.getReadId()));
        }

        if (packageLog != null) {
            if (packageTask == null) {
                return new Result().fail(0, "该任务不存在");
            }
            List<FwReadPackageTaskContent> list = readPackageTaskContentService.list(Wrappers.<FwReadPackageTaskContent>lambdaQuery().eq(FwReadPackageTaskContent::getTaskId, id).eq(FwReadPackageTaskContent::getUserId, userId));
            if (list.size() >= packageTask.getTaskNum()) {
                return success();
            }
            Builder.of(FwReadPackageTaskContent::new)
                    .with(FwReadPackageTaskContent::setId, idXD.nextId())
                    .with(FwReadPackageTaskContent::setCreateTime, LocalDateTime.now())
                    .with(FwReadPackageTaskContent::setUserId, userId)
                    .with(FwReadPackageTaskContent::setReadId, packageTask.getReadId())
                    .with(FwReadPackageTaskContent::setUserNum, 1)
                    .with(FwReadPackageTaskContent::setTaskId, id)
                    .with(FwReadPackageTaskContent::setTaskAmount, packageTask.getTaskAmount()).build().insert();
            //给红包累加额度

            readPackageLogService.updateById(packageLog.setStartNum(packageLog.getStartNum().add(packageTask.getTaskAmount())));
            return success();
        }
        return success();
    }

    //每次任务提交后调用这个后不够拆红包提现(来个动画效果)
    @GetMapping("/openRed")
    @ApiOperation("详情页面拆红包提现(来个动画效果) 红包id ")
    @Transactional(rollbackFor = Exception.class)
    public Result openRed(@RequestParam String id) {
        FwReadPackageLog packageLog = readPackageLogService.getOne(Wrappers.<FwReadPackageLog>lambdaQuery().eq(FwReadPackageLog::getReadId, id).eq(FwReadPackageLog::getUserId, this.getUser().getId()));
       if (packageLog.getIsState().equals(4)){
           return new Result().fail(0, "已领取！");
       }
        if (packageLog.getAmountNum().compareTo(packageLog.getStartNum()) <= 0) {
            //todo 发放的逻辑 发放满额积分 标记为结束
            packageLog.setIsState(4);
            readPackageLogService.updateById(packageLog);
            FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, packageLog.getUserId()));
            moneysService.updateById(moneys.setIntegral(moneys.getIntegral().add(packageLog.getAmountNum())));
            //添加日志
            logsService.saveLogs(packageLog.getUserId(), packageLog.getUserId(), LogsTypeEnum.INTEGRAL_RELEASE.getTypeName(), LogsModelEnum.INTEGRAL_MODEL.getModelName(), packageLog.getAmountNum() + "积分红包", packageLog.getAmountNum().toString());
            //
            return success(packageLog);
        }
        return new Result().fail(0, "不能拆红包");
    }


    @GetMapping("/checkReadPackage")
    @ApiOperation("检测平台有没有红包任务 如果data为空平台没发布任务")
    public Result checkReadPackage() {
        FwReadPackage list = readPackageService.getOne(Wrappers.<FwReadPackage>lambdaQuery().eq(FwReadPackage::getIsState, 1));
        if (list.getEndTime().compareTo(LocalDateTime.now()) <= 0) {
            return success(new ArrayList<>());
        }
        return success(list);
    }

}

